package tt.com.warehousemanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tt.com.common.enums.AuditEnum;
import tt.com.common.enums.Status;
import tt.com.common.model.YxCommonWarehouseStock;
import tt.com.common.model.YxCommonWarehouseStockRecord;
import tt.com.common.util.*;
import tt.com.warehousemanager.service.WarehouseGoodsService;
import tt.com.warehousemanager.service.WarehouseStockRecordService;
import tt.com.warehousemanager.service.WarehouseStockService;
import tt.com.warehousemanager.vo.AuditVo;

import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Czycka
 * @date 2022/8/24 3:27
 * @description 库存记录控制类
 */
@RestController
@RequestMapping(value = "warehouse/record")
public class WarehouseStockRecordController {

    @Autowired
    WarehouseGoodsService goodsService;

    @Autowired
    WarehouseStockRecordService recordService;

    @Autowired
    WarehouseStockService stockService;

    @PostMapping(value = "insert")
    public CommonResult insert(@RequestBody YxCommonWarehouseStockRecord record, HttpSession session) {
        if (!ObjectUtil.objectIsNull(record)) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        if (recordService.insertRecord(record, "2", record.getType()) > 0) {
            return CommonResult.buildR(Status.OK, "库存记录添加成功");
        } else {
            return CommonResult.buildR(Status.SYSTEM_ERROR, "库存记录添加失败");
        }
    }

    @PostMapping(value = "delete/{id}")
    public CommonResult delete(@PathVariable String id, HttpSession session) {
        if (StringUtils.isEmpty(id)) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        Integer result = recordService.deleteRecord(Long.valueOf(id), "2");
        if (result == -1) {
            return CommonResult.buildR(Status.SYSTEM_ERROR, "库存记录不存在");
        } else if (result == -2) {
            return CommonResult.buildR(Status.SYSTEM_ERROR, "库存记录重复删除");
        } else {
            return CommonResult.buildR(Status.OK, "库存记录删除成功");
        }
    }

    @PostMapping(value = "update")
    public CommonResult update(@RequestBody YxCommonWarehouseStockRecord record, HttpSession session) {
        if (!ObjectUtil.objectIsNull(record)) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        if (recordService.updateRecord(record, "2") > 0) {
            return CommonResult.buildR(Status.OK, "库存记录修改成功");
        } else {
            return CommonResult.buildR(Status.SYSTEM_ERROR, "库存记录修改失败");
        }
    }

    @PostMapping(value = "show/page")
    public CommonResult showPage(@RequestBody PageUtil pageUtil) {
        if (pageUtil.getPageIndex() == null || pageUtil.getPageSize() == null) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        pageUtil = recordService.showStockRecordByPage(pageUtil);
        return CommonResult.buildR(Status.OK, "查询成功", pageUtil);
    }

    @PostMapping(value = "show/all")
    public CommonResult showAll() {
        return CommonResult.buildR(Status.OK, "查询成功", recordService.list());
    }

    @PostMapping(value = "show/{id}")
    public CommonResult show(@PathVariable("id") String id) {
        if (id == null) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        YxCommonWarehouseStockRecord record = recordService.getById(id);
        return record == null ? CommonResult.buildR(Status.OK, "数据为空") : CommonResult.buildR(Status.OK, "查询成功", record);
    }

    @PostMapping(value = "show/stock/page")
    public CommonResult showStock(@RequestBody PageUtil pageUtil) {
        if (pageUtil.getPageIndex() == null || pageUtil.getPageSize() == null) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        pageUtil = stockService.showByPage(pageUtil);
        return CommonResult.buildR(Status.OK, "查询成功", pageUtil);
    }

    @PostMapping(value = "show/stock/{goodsId}")
    public CommonResult showStockByGoodsId(@PathVariable("goodsId") String goodsId) {
        if (goodsId == null) {
            return CommonResult.buildR(Status.PARAM_ISNULL, "参数为空");
        }
        QueryWrapper<YxCommonWarehouseStock> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsId);
        YxCommonWarehouseStock stock = stockService.getOne(wrapper);
        return stock == null ? CommonResult.buildR(Status.OK, "数据为空") : CommonResult.buildR(Status.OK, "查询成功", stock);
    }

    @PostMapping(value = "audit")
    public CommonResult audit(@RequestBody AuditVo auditVo, HttpSession session) {
        // 使用枚举工具类返回枚举
        AuditEnum state = EnumUtil.getEnumByCode(auditVo.getAuditType(), AuditEnum.class);
        // 拼接成审核工具类
        AuditUtil auditUtil = new AuditUtil(auditVo.getAuditId(), "2", state, auditVo.getCause());
        // 判断审核结果
        Integer result = recordService.auditing(auditUtil);
        if (result == -1) {
            // 记录已审核通过
            return CommonResult.buildR(Status.OK, "该记录已通过,不允许重复审核");
        } else if (result == -2) {
            //审核成功
            return CommonResult.buildR(Status.OK, "记录不存在");
        } else if (result > 0) {
            //审核成功
            return CommonResult.buildR(Status.OK, "审核成功");
        } else {
            return CommonResult.buildR(Status.SYSTEM_ERROR, "审核失败");
        }
    }

    @PostMapping(value = "print")
    public void print() {
        QueryWrapper<YxCommonWarehouseStockRecord> wrapper = new QueryWrapper<>();
        wrapper.last("limit 2");
        List<YxCommonWarehouseStockRecord> list = recordService.list(wrapper);
        String fileName = System.getProperty("user.dir") + "/" + System.currentTimeMillis() + ".xlsx";
        // 创建一个工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        XSSFSheet sheet = workbook.createSheet();
        // 创建表头
        String[] header = new String[]{"仓库", "物品名称", "入库单价", "入库数量", "合计金额", "操作时间", "操作类型", "负责人", "生产产商", "审核状态"};
        XSSFRow rowHead = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            rowHead.createCell(i).setCellValue(header[i]);
        }
        // 创建表体
        for (int i = 1; i <= list.size(); i++) {
            XSSFRow row = sheet.createRow(i);
            row.createCell(0).setCellValue(list.get(i-1).getWarehouseId());
            row.createCell(1).setCellValue(goodsService.getById(list.get(i-1).getGoodsId()).getName());
            row.createCell(2).setCellValue(list.get(i-1).getPrice().toString());
            row.createCell(3).setCellValue(list.get(i-1).getCount().toString());
            row.createCell(4).setCellValue(list.get(i-1).getCost().toString());
            row.createCell(5).setCellValue(new DateTime(list.get(i-1).getInTime()).toString("yyyy-MM-dd HH:mm:ss"));
            row.createCell(6).setCellValue(list.get(i-1).getType().getType());
            row.createCell(7).setCellValue(list.get(i-1).getLeaderId());
            row.createCell(8).setCellValue(list.get(i-1).getManufacturers());
            row.createCell(9).setCellValue(list.get(i-1).getAuditStatus().getType());
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileName);
            workbook.write(fileOutputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
